package com.yang.wfcuser.serive.impl;

import com.alibaba.fastjson.JSON;
import com.yang.wfcuser.mapper.UserMapper;
import com.yang.wfcuser.pojo.dto.UserLoginDTO;
import com.yang.wfcuser.pojo.vo.UserListVO;
import com.yang.wfcuser.security.UserDetails;
import com.yang.wfcuser.serive.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Value("${wfcuser.jwt.secret-key}")
    private String secretKey;
    @Value("${wfcuser.jwt.duration-in-minute}")
    private long durationInMinute;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;


    @Override
    public String login(UserLoginDTO userLoginDTO) {
        log.debug("开始处理【管理员登录】的业务，参数：{}", userLoginDTO);
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                userLoginDTO.getUsername(), userLoginDTO.getPassword());
        Authentication authenticationResult
                = authenticationManager.authenticate(authentication);
        log.debug("认证通过，认证结果：{}", authenticationResult);
        log.debug("认证通过，认证结果中的当事人：{}", authenticationResult.getPrincipal());

        Date date = new Date(System.currentTimeMillis() +durationInMinute* 60 * 1000);
        UserDetails principal= (UserDetails) authenticationResult.getPrincipal();
        Map<String,Object> claims=new HashMap<>();

        claims.put("id",principal.getId());
        claims.put("username",principal.getUsername());
        Collection<GrantedAuthority> authorities = principal.getAuthorities();
        String authoritiesJsonString = JSON.toJSONString(authorities);
        claims.put("authoritiesJsonString",authoritiesJsonString);
        String jwt = Jwts.builder()
                //Header
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                //Payload
                .setClaims(claims)
                //Signature
                .setExpiration(date)
                .signWith(SignatureAlgorithm.HS256, secretKey)
                //完成
                .compact();
        //返回JWT
        log.debug("返回JWT数据，JWT：{}", jwt);
        return jwt;
    }


    @Override
    public List<UserListVO> list() {
        log.debug("开始处理【】的业务，无参数");
        List<UserListVO> list = userMapper.list();
        log.debug("即将返回查询结果：{}", list);
        return list;
    }


}
